package com.demo.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.web.config.Login;
import com.demo.web.model.Address;
import com.demo.web.model.HttpResponse;
import com.demo.web.model.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@RestController
public class GreetingController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(GreetingController.class);

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public JSONArray greeting(@RequestParam(value = "name", defaultValue = "World") String name) {

        logger.info("greeting is coming ...........................");
        String str = loadResourceString("address/address.json");
        return JSONObject.parseArray(str);
    }

    @RequestMapping(value = "/greeting2", method = {RequestMethod.GET, RequestMethod.POST})
    @Login
    public HttpResponse<List<Address>> greeting2(@RequestBody Request requestBody) {

        logger.info("greeting is coming ........................... request:{}", JSONObject.toJSONString(requestBody));
        String str = loadResourceString("address/address.json");
        return HttpResponse.ok(JSONObject.parseArray(str, Address.class));
    }

    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    public HttpResponse login(@RequestBody Request requestBody) {

        if (requestBody.getSkuNo() == 1) {
            return HttpResponse.ok("登录成功", null);
        } else {
            return HttpResponse.fail("登录失败");
        }
    }

    @GetMapping("/greeting/obj")
    public JSONObject greetingObj(@RequestParam(value = "name", defaultValue = "World") String name) {

        logger.info("greeting is coming ...........................");
        String str = loadResourceString("address/test.json");
        return JSONObject.parseObject(str);
    }

    @RequestMapping(value = "/hello", method = {RequestMethod.GET, RequestMethod.POST})
    public String home() {
        return "Hello, World!";
    }

}
